package com.iteaj.util.json.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iteaj.util.AssertUtils;
import com.iteaj.util.core.UtilsException;
import com.iteaj.util.core.UtilsType;
import com.iteaj.util.json.Json;
import com.iteaj.util.json.JsonArray;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * create time: 2018/9/20
 *
 * @author iteaj
 * @since 1.0
 */
public class FastJsonArray implements JsonArray {

    private JSONArray array;

    public FastJsonArray(JSONArray array) {
        this.array = array;
        AssertUtils.isTrue(array != null, "未传入类型为JSONArray的构造参数", UtilsType.JSON);
    }

    @Override
    public JSONArray original() {
        return this.array;
    }

    @Override
    public int size() {
        return array.size();
    }

    @Override
    public Json getJson(int index) {
        if(original().isEmpty()) return null;

        JSONObject o = original().getJSONObject(index);
        return new Fastjson(o);
    }

    @Override
    public JsonArray getJsonArray(int index) {
        if(original().isEmpty()) return null;

        JSONArray o = original().getJSONArray(index);
        return o == null ? null : o instanceof JSONArray
                ? new FastJsonArray(o) : null;
    }

    @Override
    public <T> ArrayList<T> toList(Class<T> eleType) {
        return (ArrayList<T>) original().toJavaList(eleType);
    }

    @Override
    public <E> Iterator<E> iterator() {
        Iterator<Object> iterator = original().iterator();
        List<E> e = new ArrayList<>();
        if(null != iterator) {
            iterator.forEachRemaining((item) -> {
                if(item instanceof JSONObject) e.add((E) new Fastjson((JSON) item));
                else if(item instanceof JSONArray) e.add((E) new FastJsonArray((JSONArray) item));
                else e.add((E) item);
            });
        }
        return e.iterator();
    }

    @Override
    public <T> T toArray(Class<T> arrayType) {
        if(!arrayType.isArray())
            throw new UtilsException("反序列化JsonArray, 参数类型必须是数组类型eg：Integer[].class", UtilsType.JSON);

        return JSONObject.toJavaObject(original(), arrayType);
    }

    @Override
    public String toJsonString() {
        return original().toJSONString();
    }
}
